'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var del = require('del');
var runSequence = require('run-sequence');
var $ = require('gulp-load-plugins')({
    rename: {
        'gulp-replace-task': 'replacetask',
        'gulp-watch': 'watch'
    }
});
var pkg = require('./package.json');
var AUTOPREFIXER_BROWSERS = [
    '> 1%',
    'ie >= 9',
    'ie_mob >= 9',
    'Firefox >= 19',
    'chrome >= 24',
    'safari >= 6',
    'opera >= 15',
    'ios >= 6',
    'android >= 2.1',
    'bb >= 10'
];

gulp.task('meizhuTmpClean', function () {
    del(['.tmp']).then(function (paths) {
        console.log('Deleted files and folders:\n', paths.join('\n'));
    });
});

var meizhuRelative = './';
// ***** meizhu Home start ***** //
var meizhuHome = require(meizhuRelative + 'meizhu.json');

gulp.task('meizhuHomeViews', function () {
    var src = meizhuHome.html.src;
    var revBase = meizhuRelative + meizhuHome.html.revBase;
    var dist = meizhuRelative + meizhuHome.html.dist;

    for (var i = 0; i < src.length; i++) {
        src[i] = meizhuRelative + src[i];
    };

    return gulp.src(src, {
            base: revBase
        })
        .pipe($.replace(/((?:ref=|src=|url\()['|"])\/Public(\/[^\s>"']+?\?rev=[^\s>"']+?['|"])/g, '$1../../../../run/Public$2'))
        .pipe($.revAppend())
        .pipe($.replace(/((?:ref=|src=|url\()['|"])(\.\.\/){4}run\/Public(\/[^\s>"']+?\?rev=[^\s>"']+?['|"])/g, '$1/Public$3'))
        .pipe(gulp.dest(dist));
});

gulp.task('meizhuHomeStyleRes', function(){
    var src = meizhuHome.css.res;

    for (var i = 0; i < src.length; i++) {
        src[i] = meizhuRelative + src[i];
    };

    var dist = meizhuRelative + meizhuHome.css.dist;

    return gulp.src(src)
        .pipe($.plumber())
        .pipe(gulp.dest('.tmp'))
        .pipe(gulp.dest(dist))
        .pipe($.size({
            title: 'styles resource'
        }));
});

gulp.task('meizhuHomeStyles', ['meizhuHomeStyleRes'], function () {
    var src = meizhuHome.css.src;

    for (var i = 0; i < src.length; i++) {
        src[i] = meizhuRelative + src[i];
    };

    var dist = meizhuRelative + meizhuHome.css.dist;

    return gulp.src(src)
        .pipe($.plumber())
        .pipe($.sass({
            precision: 10,
            onError: console.error.bind(console, 'Sass error:')
        }))
        .pipe($.autoprefixer({
            browsers: AUTOPREFIXER_BROWSERS,
            remove: false
        }))
        .pipe(gulp.dest('.tmp'))
        .pipe($.if('*.css', $.cleanCss()))
        .pipe(gulp.dest(dist))
        .pipe($.size({
            title: 'styles'
        }));
});

gulp.task('meizhuHomeJshint', function () {

    var src = meizhuHome.js.src;
    var srcBase = meizhuRelative + meizhuHome.js.srcBase;

    for (var i = 0; i < src.length; i++) {
        src[i] = meizhuRelative + src[i];
    };

    return gulp.src(src, {
            base: srcBase
        })
        .pipe($.jshint('meizhu.home.jshintrc'))
        .pipe($.jshint.reporter('jshint-stylish'));

});

gulp.task('meizhuHomeScripts', ['meizhuHomeJshint'], function () {

    var src = meizhuHome.js.src;

    var dist = meizhuRelative + meizhuHome.js.dist;

    return gulp.src(src)
        .pipe($.changed(dist))
        .pipe($.uglify())
        .pipe(gulp.dest(dist))
        .pipe($.size({
            title: 'scripts'
        }));
});

gulp.task('meizhuHomeImages', function () {
    var src = meizhuHome.image.src;
    for (var i = 0; i < src.length; i++) {
        src[i] = meizhuRelative + src[i];
    };

    var srcBase = meizhuRelative + meizhuHome.image.srcBase;
    var dist = meizhuRelative + meizhuHome.image.dist;

    return gulp.src(src, {
            base: srcBase
        })
        .pipe($.imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true,
        }))
        .pipe(gulp.dest(dist))
        .pipe($.size({
            title: 'scripts'
        }));

});

gulp.task('meizhuGenerateOriginal', function() {
    var src = meizhuHome.language.chinesesrc;
    var chinese = require(meizhuRelative + 'language_page/chinese.json');
    // 进行排序
    chinese = chinese.sort(function(a, b) {
        var aLength = a.match.replace(/[\u4e00-\u9fa5]/g, 'aa').length;
        var bLength = b.match.replace(/[\u4e00-\u9fa5]/g, 'aa').length;

        return bLength - aLength;
    });
    var fs = require('fs');
    var chineseJson = JSON.stringify(chinese);

    fs.writeFile('./tmp/chineseJson.json', chineseJson, 'utf8', function(err){
        if(err){
            console.log('写入文件失败');
        }else{
            console.log('保存成功');
        }
    });
    var revBase = meizhuRelative + meizhuHome.language.chinesebase;
    var dist = meizhuHome.language.originaldist;
    for (var i = 0; i < src.length; i++) {
        src[i] = meizhuRelative + src[i];
    };
    return gulp.src(src, {
        base: revBase
    })
    .pipe($.replacetask({
        patterns : chinese,
        prefix: ''
    }))
    .pipe(gulp.dest(dist));
});

gulp.task('meizhuTranslateChinese', function() {
    var languageChinese = require(meizhuRelative + 'language_page/zh_cn.json');

    var src = meizhuHome.language.originalsrc;
    var revBase = meizhuHome.language.originalbase;
    var distChinese = meizhuRelative + meizhuHome.language.chinesedist;
    return gulp.src(src, {
        base: revBase
    })
    .pipe($.replacetask({
        patterns : languageChinese,
        prefix: ''
    }))
    .pipe(gulp.dest(distChinese));
});

gulp.task('meizhuTranslateEnglish', function() {
    var languageEnglish = require(meizhuRelative + 'language_page/en_us.json');
    var src = meizhuHome.language.originalsrc;
    var revBase = meizhuHome.language.originalbase;
    var distEnglish = meizhuRelative + meizhuHome.language.englishdist;
    return gulp.src(src, {
        base: revBase
    })
    .pipe($.replacetask({
        patterns : languageEnglish,
        prefix: ''
    }))
    .pipe(gulp.dest(distEnglish));
});

gulp.task('meizhuTranslateTaiwan', function() {
    var languageTaiwan = require(meizhuRelative + 'language_page/zh_tw.json');

    var src = meizhuHome.language.originalsrc;
    var revBase = meizhuHome.language.originalbase;
    var distTaiwan = meizhuRelative + meizhuHome.language.taiwandist;
    return gulp.src(src, {
        base: revBase
    })
    .pipe($.replacetask({
        patterns : languageTaiwan,
        prefix: ''
    }))
    .pipe(gulp.dest(distTaiwan));
});

gulp.task('meizhuLanguage', function() {
    runSequence('meizhuGenerateOriginal', 'meizhuTranslateChinese', 'meizhuTranslateEnglish', 'meizhuTranslateTaiwan');
});

gulp.task('meizhuHomeClean', function () {
    del([meizhuRelative + '.tmp', meizhuRelative + meizhuHome.image.dist, meizhuRelative + meizhuHome.js.dist, meizhuRelative + meizhuHome.css.dist]).then(function (paths) {
        console.log('Deleted files and folders:\n', paths.join('\n'));
    });
});

gulp.task('meizhuHome', function (done) {
    del([meizhuRelative + '.tmp', meizhuRelative + meizhuHome.image.dist, meizhuRelative + meizhuHome.js.dist, meizhuRelative + meizhuHome.css.dist]).then(function (paths) {
        console.log('Deleted files and folders:\n', paths.join('\n'));
        runSequence('meizhuHomeStyles', ['meizhuHomeScripts', 'meizhuHomeImages'], 'meizhuHomeViews', 'meizhuLanguage');
        done();
    });
});


gulp.task('meizhuHomeWatch', function (cb) {
    var scriptsPath = meizhuHome.js.src;
    for (var i = 0; i < scriptsPath.length; i++) {
        scriptsPath[i] = meizhuRelative + scriptsPath[i];
    };
    var stylesPath = meizhuHome.css.src;
    for (var i = 0; i < stylesPath.length; i++) {
        stylesPath[i] = meizhuRelative + stylesPath[i];
    };

    scriptsPath = scriptsPath.concat(stylesPath);

    $.watch(scriptsPath, function () {
        gulp.start('meizhuHome');
    });
});

// ***** meizhu Home end ***** //
//
//
//
// ***** meizhu Book start ***** //
var meizhuBook = require(meizhuRelative + 'book.json');
gulp.task('meizhuBookStyles', function () {
    var src = meizhuBook.css.src;

    for (var i = 0; i < src.length; i++) {
        src[i] = meizhuRelative + src[i];
    };

    var dist = meizhuRelative + meizhuBook.css.dist;

    return gulp.src(src)
        .pipe($.plumber())
        .pipe($.sass({
            precision: 10,
            onError: console.error.bind(console, 'Sass error:')
        }))
        .pipe($.autoprefixer({
            browsers: AUTOPREFIXER_BROWSERS,
            remove: false
        }))
        .pipe(gulp.dest('.tmp'))
        .pipe($.if('*.css', $.cleanCss()))
        .pipe(gulp.dest(dist))
        .pipe($.size({
            title: 'styles'
        }));
});


gulp.task('meizhuBookViews', function () {
    var src = meizhuBook.html.src;
    var revBase = meizhuRelative + meizhuBook.html.revBase;
    var dist = meizhuRelative + meizhuBook.html.dist;

    for (var i = 0; i < src.length; i++) {
        src[i] = meizhuRelative + src[i];
    };

    return gulp.src(src, {
            base: revBase
        })
        .pipe($.replace(/((?:ref=|src=|url\()['|"])\/Public(\/[^\s>"']+?\?rev=[^\s>"']+?['|"])/g, '$1../../../../run/Public$2'))
        .pipe($.revAppend())
        .pipe($.replace(/((?:ref=|src=|url\()['|"])(\.\.\/){4}run\/Public(\/[^\s>"']+?\?rev=[^\s>"']+?['|"])/g, '$1/Public$3'))
        .pipe(gulp.dest(dist));
});

gulp.task('meizhuBookJshint', function () {

    var src = meizhuBook.js.src;
    var srcBase = meizhuRelative + meizhuBook.js.srcBase;

    for (var i = 0; i < src.length; i++) {
        src[i] = meizhuRelative + src[i];
    };

    return gulp.src(src, {
            base: srcBase
        })
        .pipe($.jshint('meizhu.book.jshintrc'))
        .pipe($.jshint.reporter('jshint-stylish'));

});

gulp.task('meizhuBookScripts', ['meizhuBookJshint'], function () {

    var src = meizhuBook.js.src;

    var dist = meizhuRelative + meizhuBook.js.dist;

    return gulp.src(src)
        .pipe($.changed(dist))
        .pipe($.uglify())
        .pipe(gulp.dest(dist))
        .pipe($.size({
            title: 'scripts'
        }));
});

gulp.task('meizhuBookImages', function () {
    var src = meizhuBook.image.src;
    for (var i = 0; i < src.length; i++) {
        src[i] = meizhuRelative + src[i];
    };

    var srcBase = meizhuRelative + meizhuBook.image.srcBase;
    var dist = meizhuRelative + meizhuBook.image.dist;

    return gulp.src(src, {
            base: srcBase
        })
        .pipe($.imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true,
        }))
        .pipe(gulp.dest(dist))
        .pipe($.size({
            title: 'scripts'
        }));

});

gulp.task('bookGenerateOriginal', function() {
    var src = meizhuBook.language.chinesesrc;
    var chinese = require(meizhuRelative + 'language_page/chinese.json');
    // 进行排序
    chinese = chinese.sort(function(a, b) {
        var aLength = a.match.replace(/[\u4e00-\u9fa5]/g, 'aa').length;
        var bLength = b.match.replace(/[\u4e00-\u9fa5]/g, 'aa').length;

        return bLength - aLength;
    });
    var fs = require('fs');
    var chineseJson = JSON.stringify(chinese);

    fs.writeFile('./tmp/chineseJson.json', chineseJson, 'utf8', function(err){
        if(err){
            console.log('写入文件失败');
        }else{
            console.log('保存成功');
        }
    });
    var revBase = meizhuRelative + meizhuBook.language.chinesebase;
    var dist = meizhuBook.language.originaldist;
    for (var i = 0; i < src.length; i++) {
        src[i] = meizhuRelative + src[i];
    };
    return gulp.src(src, {
        base: revBase
    })
    .pipe($.replacetask({
        patterns : chinese,
        prefix: ''
    }))
    .pipe(gulp.dest(dist));
});

gulp.task('bookTranslateChinese', function() {
    var languageChinese = require(meizhuRelative + 'language_page/zh_cn.json');

    var src = meizhuBook.language.originalsrc;
    var revBase = meizhuBook.language.originalbase;
    var distChinese = meizhuRelative + meizhuBook.language.chinesedist;
    return gulp.src(src, {
        base: revBase
    })
    .pipe($.replacetask({
        patterns : languageChinese,
        prefix: ''
    }))
    .pipe(gulp.dest(distChinese));
});

gulp.task('bookTranslateEnglish', function() {
    var languageEnglish = require(meizhuRelative + 'language_page/en_us.json');
    var src = meizhuBook.language.originalsrc;
    var revBase = meizhuBook.language.originalbase;
    var distEnglish = meizhuRelative + meizhuBook.language.englishdist;
    return gulp.src(src, {
        base: revBase
    })
    .pipe($.replacetask({
        patterns : languageEnglish,
        prefix: ''
    }))
    .pipe(gulp.dest(distEnglish));
});

gulp.task('bookTranslateTaiwan', function() {
    var languageTaiwan = require(meizhuRelative + 'language_page/zh_tw.json');

    var src = meizhuBook.language.originalsrc;
    var revBase = meizhuBook.language.originalbase;
    var distTaiwan = meizhuRelative + meizhuBook.language.taiwandist;
    return gulp.src(src, {
        base: revBase
    })
    .pipe($.replacetask({
        patterns : languageTaiwan,
        prefix: ''
    }))
    .pipe(gulp.dest(distTaiwan));
});

gulp.task('bookLanguage', function() {
    runSequence('bookGenerateOriginal', 'bookTranslateChinese', 'bookTranslateEnglish', 'bookTranslateTaiwan');
});

gulp.task('meizhuBook', function (done) {
    runSequence('meizhuBookStyles', ['meizhuBookScripts'], 'meizhuBookViews', 'meizhuBookImages','bookLanguage');
    done();
});

gulp.task('meizhuBookWatch', function (cb) {
    var scriptsPath = meizhuBook.js.src;
    for (var i = 0; i < scriptsPath.length; i++) {
        scriptsPath[i] = meizhuRelative + scriptsPath[i];
    };
    var stylesPath = meizhuBook.css.src;
    for (var i = 0; i < stylesPath.length; i++) {
        stylesPath[i] = meizhuRelative + stylesPath[i];
    };

    scriptsPath = scriptsPath.concat(stylesPath);

    $.watch(scriptsPath, function () {
        gulp.start('meizhuBook');
    });
});
// ***** meizhu Book end ***** //
